package net.wicp.tams.common.binlog.self.bean;

import java.io.IOException;
import java.io.InputStream;

import lombok.Builder;
import lombok.Data;
import net.wicp.tams.common.binlog.self.LogBuffer;
import net.wicp.tams.common.binlog.self.constant.Checksum;
import net.wicp.tams.common.io.InputStreamAssit;

@Data
@Builder
public class PacketBean {
	private int sequence;
	private LogBuffer body;

	// 扩展
	private byte packetMarker;
	private EventBean eventBean;

	public int getLength() {
		return body.capacity() - 1;
	}

	public static PacketBean buildBean(InputStream in) throws IOException {
		InputStreamAssit isAssit = new InputStreamAssit(in);
		int length = isAssit.readInt(3);
		int sequence = isAssit.readInt(1);
		byte[] body = isAssit.readBytes(length);
		byte packetMarker = body[0];
		return PacketBean.builder().sequence(sequence).body(new LogBuffer(body, 0, body.length))
				.packetMarker(packetMarker).build();
	}

	public static PacketBean buildEventBean(InputStream in, String fileName, String gtids, Checksum checksum)
			throws IOException {
		InputStreamAssit isAssit = new InputStreamAssit(in);

		int length = isAssit.readInt(3);
		int sequence = isAssit.readInt(1);
		byte[] body = isAssit.readBytes(length);
		if (length == 0) {
			throw new RuntimeException(String.format("接出的socket出现异常，服务将退出.fileName:%s,gtids:%s", fileName, gtids));
		}
		byte packetMarker = body[0];

		LogBuffer logBuffer = new LogBuffer(body, 0, body.length - checksum.getByteNum());// TableMap不需要这个
		// checksum.getByteNum()
		EventBean eventBean = new EventBean(logBuffer);// 跳过较验位//
		eventBean.setFileName(fileName);
		eventBean.setGtids(gtids);
		eventBean.setChecksum(checksum);
		return PacketBean.builder().sequence(sequence).body(logBuffer).packetMarker(packetMarker).eventBean(eventBean)
				.build();
	}

}
